import CommonModalTemplate from '@/components/common-modal-template/common-modal-template';
import { guid } from '@/util/helpers';
import CommonDataTablesTemplate from '@/components/common-dataTables-template/common-dataTables-template';
import { addOrUpdateApi, getApiInfo } from '@/api/product/station-manage';
export default {
  components: {
    CommonModalTemplate,
    CommonDataTablesTemplate
  },
  data() {
    return {
      tabsIndex: '1',
      //初始数据加载书写
      apiInfo: {}, //基础信息
      apiInfoOption: {
        //基础信息内容配置
        submitBtn: false,
        emptyBtn: false,
        labelWidth: '110',
        labelPosition: 'top',
        column: [
          {
            label: 'API响应名称',
            prop: 'name',
            span: 4,
            rules: [
              {
                required: true,
                trigger: 'submit',
                validator: (rule, value, callback) => {
                  callback();
                }
              }
            ]
          },
          {
            label: 'API响应编码',
            prop: 'code',
            span: 4,
            rules: [
              {
                required: true,
                trigger: 'submit',
                validator: (rule, value, callback) => {
                  callback();
                }
              }
            ]
          },
          {
            label: 'API地址',
            prop: 'url',
            span: 6,
            value: '/api/mes-product/apaas/api/command/query/execute',
            rules: [
              {
                required: true,
                trigger: 'submit',
                validator: (rule, value, callback) => {
                  callback();
                }
              }
            ]
          },
          {
            label: '备注',
            prop: 'remark',
            span: 4
          },
          {
            label: '返回集合配置别名',
            prop: 'aliasName',
            span: 4
          }
        ]
      },
      returnTypeOption: {
        //响应类型表单配置
        submitBtn: false,
        emptyBtn: false,
        labelWidth: '110',
        labelPosition: 'top',
        column: [
          {
            label: '响应类型',
            prop: 'returnType',
            type: 'select',
            value: '结果',
            dicData: [
              {
                label: '结果',
                value: '结果'
              },
              {
                label: '分组',
                value: '分组'
              }
            ],
            span: 4,
            rules: [
              {
                required: true,
                trigger: 'submit',
                validator: (rule, value, callback) => {
                  callback();
                }
              }
            ],
            change: () => {
              this.returnFields = [];
              this.groupFields = [];
            }
          }
        ]
      },
      configSqlOption: {
        //响应类型表单配置
        submitBtn: false,
        emptyBtn: false,
        labelWidth: '110',
        labelPosition: 'top',
        column: [
          {
            label: 'SQL配置',
            prop: 'configSql',
            type: 'textarea',
            minRows: 4,
            // maxRows: 3,
            span: 24
          }
        ]
      },
      apiFlowId: '',

      paramsList: [], //参数配置
      paramsData: [], //参数信息配置数据
      paramsOption: {
        border: true, //是否显示表格框线
        stripe: true, //是否显示条纹
        showHeader: true, //是否显示表头
        index: true, //是否显示表格序号
        indexLabel: '序号',
        addBtn: false, //新增按钮是否显示
        editBtn: false, //行编辑按钮是否显示
        refreshBtn: false, //刷新按钮是否显示
        columnBtn: false,
        filterBtn: false, //表格列过滤按钮是否显示
        height: 250,
        selection: false,
        column: [
          {
            label: '字段',
            prop: 'code'
          },
          {
            label: '字段注释',
            prop: 'value'
          }
        ]
      }, //参数信息配置表格配置属性
      dataTables: [], //表数据以及关系
      dataTablesOption: {
        //表信息表格配置
        height: 250,
        calcHeight: 30,
        border: true,
        index: true,
        indexLabel: '序号',
        selection: false,
        addBtn: false,
        addRowBtn: true,
        cellBtn: true,
        column: [
          {
            label: '表名称',
            prop: 'tableName',
            type: 'search',
            cell: true,
            appendClick: () => {
              this.openCommonTableModal('update');
            }
          },
          {
            label: '表注释',
            prop: 'tableNotes'
          },
          {
            label: '表别名',
            prop: 'tableAlias',
            cell: true
          },
          {
            label: '表别名注释',
            prop: 'tableAliasNotes',
            cell: true
          },
          {
            label: '关联关系',
            prop: 'tableRelation',
            cell: true
          }
        ]
      },
      dataTablesIndex: 0, //表数据以及关系当前编辑行索引
      dataTablesType: '', //表数据以及关系选择类型

      conditionsDefaults: {},
      conditions: [], //表条件
      conditionsOption: {
        //条件信息表格配置
        height: 250,
        calcHeight: 30,
        border: true,
        index: true,
        indexLabel: '序号',
        selection: false,
        addBtn: false,
        viewBtn: false,
        addRowBtn: true,
        cellBtn: true,
        column: [
          {
            label: '字段名称',
            prop: 'field',
            type: 'search',
            width: 200,
            cell: true,
            appendClick: () => {
              this.openCommonTableFieldModal('conditions', this.conditionsRowIndex);
            }
          },
          {
            label: '字段注释',
            prop: 'fieldNotes'
          },
          {
            label: '表名',
            prop: 'tableName'
          },
          {
            label: '表别名',
            prop: 'tableAlias'
          },
          {
            label: '运算符',
            prop: 'operator',
            type: 'select',
            dicData: [
              {
                label: '请选择',
                value: ''
              },
              {
                label: '等于',
                value: '等于'
              },
              {
                label: '大于',
                value: '大于'
              },
              {
                label: '小于',
                value: '小于'
              },
              {
                label: '包含',
                value: '包含'
              },
              {
                label: '小于等于',
                value: '小于等于'
              },
              {
                label: '大于等于',
                value: '大于等于'
              },
              {
                label: '空值',
                value: '空值'
              }
            ],
            cell: true
          },
          {
            label: '逻辑连接符',
            prop: 'connector',
            type: 'select',
            dicData: [
              {
                label: '请选择',
                value: ''
              },
              {
                label: '且',
                value: '且'
              },
              {
                label: '或',
                value: '或'
              }
            ],
            cell: true
          },
          {
            label: '连接符优先级',
            prop: 'connectorPriority',
            type: 'number',
            cell: true
          },
          {
            label: '参数值类型',
            prop: 'type',
            type: 'select',
            dicData: [
              {
                label: '请选择',
                value: ''
              },
              {
                label: '输入参数',
                value: '输入参数'
              },
              {
                label: '设定值',
                value: '设定值'
              }
            ],
            cell: true,
            change: (val) => {
              if (val.value === '输入参数') {
                this.conditionsDefaults.value.type = 'select';
              } else {
                this.conditionsDefaults.value.type = 'input';
              }
            }
          },
          {
            label: '输入参数/设定值',
            prop: 'value',
            type: 'select',
            cell: true,
            dicData: [],
            props: {
              label: 'value',
              value: 'code'
            }
          }
        ]
      },
      conditionsRowIndex: 0, //条件信息行下标
      sorts: [], //表排序
      sortsOption: {
        //排序配置表格配置
        height: 250,
        calcHeight: 30,
        border: true,
        index: true,
        indexLabel: '序号',
        selection: false,
        addBtn: false,
        viewBtn: false,
        addRowBtn: true,
        cellBtn: true,
        column: [
          {
            label: '字段名称',
            prop: 'field',
            type: 'search',
            width: 200,
            cell: true,
            appendClick: (value) => {
              console.log(value);
              this.openCommonTableFieldModal('sorts', this.conditionsRowIndex);
            }
          },
          {
            label: '字段注释',
            prop: 'fieldNotes'
          },
          {
            label: '表名',
            prop: 'tableName'
          },
          {
            label: '表别名',
            prop: 'tableAlias'
          },
          {
            label: '排序类型',
            prop: 'sortType',
            type: 'select',
            dicData: [
              {
                label: '请选择',
                value: ''
              },
              {
                label: '升序',
                value: '升序'
              },
              {
                label: '降序',
                value: '降序'
              }
            ],
            cell: true
          }
        ]
      },
      groupFields: [], //表分组
      groupFieldsOption: {
        //分组字段配置表格配置
        height: 250,
        calcHeight: 30,
        border: true,
        index: true,
        indexLabel: '序号',
        selection: false,
        addBtn: false,
        viewBtn: false,
        addRowBtn: true,
        cellBtn: true,
        column: [
          {
            label: '字段名称',
            prop: 'field',
            type: 'search',
            width: 200,
            cell: true,
            appendClick: (value) => {
              this.openCommonTableFieldModal('groupFields', this.conditionsRowIndex);
            }
          },
          {
            label: '字段注释',
            prop: 'fieldNotes'
          },
          {
            label: '表名',
            prop: 'tableName'
          },
          {
            label: '表别名',
            prop: 'tableAlias'
          }
        ]
      },
      returnFieldsDefaults: {},
      returnFields: [], //表返回字段信息
      returnFieldsOption: {
        //返回字段配置表格、聚合配置表格配置
        height: 250,
        calcHeight: 30,
        border: true,
        index: true,
        indexLabel: '序号',
        selection: false,
        addBtn: false,
        viewBtn: false,
        addRowBtn: true,
        cellBtn: true,
        column: [
          {
            label: '字段名称',
            prop: 'field',
            width: 200
          },
          {
            label: '字段注释',
            prop: 'fieldNotes'
          },
          {
            label: '字段别名',
            prop: 'fieldAlias',
            cell: true
          },
          {
            label: '表名',
            prop: 'tableName'
          },
          {
            label: '表别名',
            prop: 'tableAlias'
          },
          {
            label: '数据类型',
            prop: 'dataType',
            type: 'select',
            dicData: [
              {
                label: '请选择',
                value: ''
              },
              {
                label: '字段',
                value: '字段'
              },
              {
                label: '子查询',
                value: '子查询'
              }
            ],
            cell: true,
            change: (val) => {
              if (val.value === '字段' || val.value === '') {
                this.returnFieldsDefaults.mappingApiName.type = 'input';
                this.returnFieldsDefaults.mappingApiName.cell = false;
              } else {
                this.returnFieldsDefaults.mappingApiName.type = 'search';
                this.returnFieldsDefaults.mappingApiName.cell = true;
              }
            }
          },
          {
            label: '数据映射',
            prop: 'mappingApiName',
            type: 'input',
            cell: false,
            appendClick: (value) => {
              this.openQueryApiModal(this.conditionsRowIndex);
            }
          },
          {
            label: '聚合类型',
            prop: 'operationMode',
            type: 'select',
            dicData: [
              {
                label: '求和',
                value: '求和'
              },
              {
                label: '平均值',
                value: '平均值'
              },
              {
                label: '最大值',
                value: '最大值'
              },
              {
                label: '最小值',
                value: '最小值'
              },
              {
                label: '对行进行计数',
                value: '对行进行计数'
              },
              {
                label: '所有行',
                value: '所有行'
              }
            ],
            cell: true
          }
        ]
      },
      returnFieldsIndex: 0,
      tableOption: {}, //公用模态框表格属性
      isTableRelationModal: false, //配置表关联关系表是否显示
      modalName: '',
      timer: new Date().getTime(),
      tableFieldType: '',
      tableFieldIndex: 0,
      tableFieldType: '', //选择表字段类型
      associationConditions: [], //表关联关系信息
      associationConditionsOption: {
        height: 'calc(100vh - 480px)',
        calcHeight: 30,
        border: true,
        index: true,
        indexLabel: '序号',
        selection: false,
        addBtn: false,
        viewBtn: false,
        addRowBtn: true,
        cellBtn: true,
        menuWidth: 150,
        column: [
          {
            label: '左表字段',
            prop: 'leftField',
            width: 200,
            cell: true,
            type: 'search',
            appendClick: () => {
              this.openCommonTableFieldModal('associationConditionsLeft', this.conditionsRowIndex);
            }
          },
          {
            label: '左表字段注释',
            prop: 'leftFieldNotes'
          },
          {
            label: '运算符',
            prop: 'operator',
            type: 'select',
            cell: true,
            dicData: [
              {
                label: '等于',
                value: '等于'
              },
              {
                label: '大于',
                value: '大于'
              },
              {
                label: '小于',
                value: '小于'
              },
              {
                label: '包含',
                value: '包含'
              },
              {
                label: '小于等于',
                value: '小于等于'
              },
              {
                label: '大于等于',
                value: '大于等于'
              }
            ]
          },
          {
            label: '右表字段',
            prop: 'rightField',
            width: 200,
            cell: true,
            type: 'search',
            appendClick: () => {
              this.openCommonTableFieldModal('associationConditionsRight', this.conditionsRowIndex);
            }
          },
          {
            label: '右表字段注释',
            prop: 'rightFieldNotes'
          },
          {
            label: '逻辑连接符',
            prop: 'connector',
            type: 'select',
            cell: true,
            dicData: [
              {
                label: '且',
                value: '且'
              },
              {
                label: '或',
                value: '或'
              }
            ]
          },
          {
            label: '连接符优先级',
            prop: 'connectorPriority',
            cell: true
          },
          {
            label: '类型',
            prop: 'type',
            type: 'select',
            cell: true,
            dicData: [
              {
                label: '表连接',
                value: '表连接'
              },
              {
                label: '设定值',
                value: '设定值'
              },
              {
                label: '输入参数',
                value: '输入参数'
              }
            ]
          },
          {
            label: '表连接/设定值/输入参数',
            prop: 'value',
            cell: true,
            width: 180
          }
        ]
      }, //表关联关系配置
      associationConditionsIndex: 0 //表关联关系选中行下标
    };
  },
  watch: {
    isTableRelationModal(val) {
      if (val) {
        setTimeout(() => {
          console.log(this.dataTablesIndex);
          this.associationConditions = this.dataTables[this.dataTablesIndex].associationConditions;
        });
      }
    }
  },
  computed: {},

  created() {
    if (this.$route.query.apiId) {
      this.apiFlowId = this.$route.query.apiId;
      this.getModelFlowInfo(this.apiFlowId);
    }
  },

  mounted() {},
  methods: {
    handleTabClick() {},
    /**
     * 通过工站ID查询工站信息
     * @param apiFlowId
     */
    getModelFlowInfo(apiId) {
      if (apiId) {
        getApiInfo(apiId).then((res) => {
          if (res.data) {
            this.apiInfo = res.data.data;

            //参数信息配置
            this.paramsData = this._get(this.apiInfo, 'paramsJson', '');
            this.paramsData = this.paramsData ? JSON.parse(this.paramsData) : [];
            this.conditionsDefaults.value.dicData = this.paramsData;

            //表配置信息
            this.dataTables = this._get(this.apiInfo, 'dataTables', '');
            this.dataTables = this.dataTables ? JSON.parse(this.dataTables) : [];
            console.log(this.dataTables);
            this._forEach(this.dataTables, (item) => {
              let tableRelation = '';
              this._forEach(item.associationConditions, (associationItem) => {
                tableRelation += `${associationItem.leftFieldNotes} ${associationItem.operator} ${associationItem.rightFieldNotes} ${associationItem.connector}  ${associationItem.type}`;
              });
              item.tableRelation = tableRelation;
            });
            //条件配置信息
            this.conditions = this._get(this.apiInfo, 'conditions', '');
            this.conditions = this.conditions ? JSON.parse(this.conditions) : [];
            //排序信息
            this.sorts = this._get(this.apiInfo, 'sorts', '');
            this.sorts = this.sorts ? JSON.parse(this.sorts) : [];

            let returnFields = this._get(this.apiInfo, 'returnFields', '');
            returnFields = returnFields ? JSON.parse(returnFields) : [];
            this.apiInfo.returnType = this._get(returnFields, '[0].type', '结果');
            setTimeout(() => {
              //返回信息配置OR聚合信息配置
              this.returnFields = returnFields;
              //表字段分组信息
              this.groupFields = this._get(this.apiInfo, 'groupFields', '');
              this.groupFields = this.groupFields ? JSON.parse(this.groupFields) : [];
            }, 500);
          } else {
            this.apiInfo = {};
            this.selectedNodeInfo = {};
            this.apiInfo.returnType = '结果';
          }
        });
      } else {
        this.apiInfo = {};
        this.selectedNodeInfo = {};
        this.apiInfo.returnType = '结果';
      }
    },

    /**
     * 打开常用参数模态框
     */
    openCommonParamsModal() {
      this.modalName = 'paramsModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择常用参数（请点击复选框进行多选）',
        url: '/api/blade-system/dict/dictionary?code=STATION_CENTER_PARAMS_LIST',
        isPage: false,
        rowSelectionType: 'multiple',
        columnDefs: [
          {
            label: '参数',
            prop: 'dictKey',
            search: true
          },
          {
            label: '注释',
            prop: 'dictValue',
            search: true
          },
          {
            label: '序号',
            prop: 'sort'
          },
          {
            label: '备注',
            prop: 'remark'
          }
        ]
      };
    },

    /**
     * 参数信息配置删除表格数据
     */
    paramsRowDel(row, index) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.paramsData.splice(index, 1);
          this.paramsList.splice(index, 1);
        })
        .then(() => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        });
    },

    /**
     * 打开常用表模态框
     */
    openCommonTableModal(type) {
      this.dataTablesType = type;
      this.modalName = 'tableModal';
      //限制关联关系必须填写
      if (this.dataTables.length >= 2) {
        if (this.dataTables[this.dataTables.length - 1].associationConditions.length === 0) {
          this.$confirm('请编辑表关联关系！', '提示', {
            confirmButtonText: '确定',
            type: 'warning'
          });
          return;
        }
      }
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择常用表（请双击进行选择）',
        url: '/api/mes-product/apaas/tabcolumns/page',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '表名称',
            prop: 'tabname',
            search: true
          },
          {
            label: '表注释',
            prop: 'tabcomment',
            search: true
          }
        ]
      };
    },

    /**
     * 表信息配置行点击事件
     */
    dataTablesRowClick(row) {
      this.dataTablesIndex = row.$index;
    },

    /**
     * 表信息配置行保存
     */
    dataTablesRowSave(row, done) {
      this.dataTables[row.$index].$cellEdit = false;
      done();
    },

    /**
     * 表信息配置行编辑
     */
    dataTablesRowUpdate(row, index, done) {
      this.dataTables[index].$cellEdit = false;
      done();
    },

    /**
     * 表信息配置行删除
     */
    dataTablesRowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return this.dataTables.splice(row.$index, 1);
      });
    },

    /**
     * 打开编辑表关联关系模态框
     * @param index
     */
    openEditRationModal(index) {
      this.dataTablesIndex = index;
      this.isTableRelationModal = true;
      this.associationConditions = this.dataTables[index].associationConditions;
      console.log(this.associationConditions);
    },

    /**
     * 保存条件信息配置表格行数据
     * @param form
     * @param done
     */
    conditionsRowSave(form, done) {
      this.$message.success('条件信息保存成功！');
      done();
    },

    /**
     * 编辑条件信息配置表格行数据
     */
    conditionsAddUpdate(form, index, done) {
      this.$message.success('条件信息编辑成功！');
      done();
    },

    /**
     * 删除条件信息配置表格行数据
     */
    conditionsRowDel(row, index) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.conditions.splice(index, 1);
        })
        .then(() => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        });
    },

    /**
     * 排序配置表格行数据保存
     */
    sortsRowSave(form, done) {
      this.$message.success('条件信息保存成功！');
      done();
    },

    /**
     * 排序配置表格行数据编辑
     */
    sortsAddUpdate(form, index, done) {
      this.$message.success('条件信息编辑成功！');
      done();
    },

    /**
     * 删除排序配置表格行数据
     */
    sortsRowDel(row, index) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.sorts.splice(index, 1);
        })
        .then(() => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        });
    },

    /**
     * 返回字段配置、聚合配置表行数据保存
     */
    returnFieldsRowSave(form, done) {
      if (this.apiInfo.returnType === '结果') {
        this.$message.success('返回字段配置保存成功！');
      } else {
        this.$message.success('聚合配置保存成功！');
      }
      done();
    },

    /**
     * 返回字段配置、聚合配置表行数据编辑
     */
    returnFieldsAddUpdate(form, index, done) {
      if (this.apiInfo.returnType === '结果') {
        this.$message.success('返回字段配置编辑成功！');
      } else {
        this.$message.success('聚合配置编辑成功！');
      }
      done();
    },

    /**
     * 返回字段配置、聚合配置表行数据删除
     */
    returnFieldsRowDel(row, index) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.returnFields.splice(index, 1);
        })
        .then(() => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        });
    },

    /**
     * 新增表关联关系表
     */
    associationConditionsRowSave(form, done) {
      this.$message.success('表关联关系保存成功！');
      done();
    },

    /**
     * 编辑表关联关系
     */
    associationConditionsAddUpdate(form, index, done) {
      this.$message.success('表关联关系保存成功！');
      done();
    },
    /**
     * 删除表关联关系
     */
    associationConditionsRowDel(row, index) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.associationConditions.splice(index, 1);
        })
        .then(() => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        });
    },

    /**
     * 表关联关系保存
     */
    saveAssociationConditions() {
      this.dataTables[this.dataTablesIndex].associationConditions = this.associationConditions;
      this._forEach(this.dataTables, (item, itemIndex) => {
        if (this.dataTablesIndex === itemIndex) {
          let tableRelation = '';
          this._forEach(item.associationConditions, (associationItem, index) => {
            tableRelation += `${associationItem.leftFieldNotes} ${associationItem.operator} ${associationItem.rightFieldNotes} ${associationItem.connector} ${associationItem.type}`;
          });
          item.tableRelation = tableRelation;
        }
      });
      this.isTableRelationModal = false;
    },

    /**
     * 移除表格行数据
     * @param type 表格类型
     * @param index 索引
     */
    removeTableRow(type, index) {
      //移除所有已选择了该表的字段信息
      if (type === 'dataTables') {
        let insideCode = this._get(this[type][index], 'insideCode', '');
        this.associationConditions = this._filter(this.associationConditions, (item) => {
          return item.leftInsideCode !== insideCode || item.rightInsideCode !== insideCode;
        });
        this.conditions = this._filter(this.conditions, (item) => {
          return item.insideCode !== insideCode;
        });
        this.sorts = this._filter(this.sorts, (item) => {
          return item.insideCode !== insideCode;
        });
        this.groupFields = this._filter(this.groupFields, (item) => {
          return item.insideCode !== insideCode;
        });
        this.returnFields = this._filter(this.returnFields, (item) => {
          return item.insideCode !== insideCode;
        });
      }
      this[type].splice(index, 1);
    },

    /**
     * 打开选择表字段模态框组件(单选)
     */
    openCommonTableFieldModal(type, index) {
      this.tableFieldType = type;
      this.conditionsRowIndex = index;
      let tables = [];
      if (type === 'associationConditionsLeft' || type === 'associationConditionsRight') {
        console.log(this.dataTables);
        tables = this._map(this._cloneDeep(this.dataTables), (item, itemIndex) => {
          if (itemIndex <= this.dataTablesIndex) {
            if (item.tableAlias) {
              item.tableComment = item.tableNotes + '-' + item.tableAlias;
            } else {
              item.tableComment = item.tableNotes;
            }
            return item;
          }
        });
      } else {
        tables = this._map(this._cloneDeep(this.dataTables), (item) => {
          if (item.tableAlias) {
            item.tableComment = item.tableNotes + '-' + item.tableAlias;
          } else {
            item.tableComment = item.tableNotes;
          }
          return item;
        });
      }

      this._forEach(tables, (item, index) => {
        if (item === undefined) {
          tables.splice(index, 1);
        }
        //选了两张相同的表时给表名拼接上表别名供选表字段时切换表
        if (item.tableAlias) {
          item.tableName = item.tableName + '-' + item.tableAlias;
        }
      });

      //获取表信息配置中已经选择好的表
      if (this.dataTables.length > 0) {
        this.modalName = 'tableFieldModal';
        //限制关联关系必须填写
        if (this.dataTables.length >= 2) {
          if (this.dataTables[this.dataTables.length - 1].associationConditions.length === 0) {
            this.$confirm('请编辑表关联关系！', '提示', {
              confirmButtonText: '确定',
              type: 'warning'
            });
            return;
          }
        }
        this.$refs.commonDataTablesTemplate.showModal();
        this.tableOption = {
          modalTitle: '选择表字段（请双击进行选择）',
          url: '/api/mes-product/apaas/tabcolumns/col/page',
          isPage: true,
          rowSelectionType: 'single',
          columnDefs: [
            {
              label: '字段名',
              prop: 'colname',
              search: true
            },
            {
              label: '字段注释',
              prop: 'colcomment',
              search: true
            },
            {
              label: '表名',
              prop: 'tabname',
              search: true,
              searchOrder: 1,
              type: 'select',
              dicData: tables,
              props: {
                label: 'tableComment',
                value: 'tableName'
              },
              searchValue: this._get(tables, '[0].tableName', '')
            },
            {
              label: '表注释',
              prop: 'tabcomment'
            }
          ]
        };
      } else {
        this.$alert('请先新增表信息', '提示', {
          confirmButtonText: '确定'
        });
        // if (type === 'returnFields' && this.dataTables.length === 0) {
        //   this.$confirm('当前未配置表信息，如果继续操作将添加自定义字段', '提示', {
        //     confirmButtonText: '确定',
        //     type: 'warning'
        //   }).then(() => {
        //     this.modalName = 'returnFields'
        //     this.$refs.commonModalTemplate.showModal();
        //     this.tableOption = {
        //       modalTitle: '选择表字段（请双击进行选择）',
        //       url: '/api/mes-product/apaas/tabcolumns/col/page',
        //       isPage: true,
        //       rowSelectionType: 'single',
        //       columnDefs: [
        //         {
        //           label: '字段名',
        //           prop: 'colname',
        //           search: true
        //         },
        //         {
        //           label: '字段注释',
        //           prop: 'colcomment',
        //           search: true
        //         }
        //       ]
        //     };
        //   });
        // } else {
        //   this.$alert('请先新增表信息', '提示', {
        //     confirmButtonText: '确定'
        //   });
        // }
      }
    },

    getDataTablesSelectedRows(data) {
      let list = this.tableFieldType;
      console.log(list);
      let repertField = this._find(list, { field: data.fieldName, insideCode: data.insideCode });
      if (repertField) {
        this.$confirm('当前选中的字段已经被添加过了，请重新选择！', '提示', {
          confirmButtonText: '确定',
          type: 'warning'
        });
        return;
      }
      this._forEach(list, (item) => {
        // item['$cellEdit'] = false;
      });
      console.log(this.tableFieldType);
      console.log(this.conditionsRowIndex);
      switch (this.tableFieldType) {
        case 'associationConditionsLeft':
          this._forEach(this.associationConditions, (item, itemIndex) => {
            if (this.associationConditionsIndex === itemIndex) {
              item.leftInsideCode = data.insideCode;
              item.leftField = data.colname;
              item.leftFieldNotes = data.colcomment;
              item.leftTableName = data.tabname;
              item.leftTableAlias = data.tableAlias;
            }
            console.log(this.associationConditions);
          });
          break;
        case 'associationConditionsRight':
          this._forEach(this.associationConditions, (item, itemIndex) => {
            if (this.associationConditionsIndex === itemIndex) {
              item.rightInsideCode = data.insideCode;
              item.rightField = data.colname;
              item.rightFieldNotes = data.colcomment;
              item.rightTableName = data.tabname;
              item.rightTableAlias = data.tableAlias;
            }
            console.log(this.associationConditions);
          });
          break;
        case 'conditions':
          if (this.conditionsRowIndex === null) {
            this.conditions.push({
              insideCode: data.insideCode,
              field: data.colname,
              fieldNotes: data.colcomment,
              tableName: data.tabname,
              tableAlias: data.tableAlias,
              connector: '', //逻辑连接符
              connectorPriority: '',
              operator: '',
              type: '输入参数',
              value: '',
              sequence: '',
              $cellEdit: true
            });
          } else {
            this._forEach(this.conditions, (item, itemIndex) => {
              if (this.conditionsRowIndex === itemIndex) {
                item.insideCode = data.insideCode;
                item.field = data.colname;
                item.fieldNotes = data.colcomment;
                item.tableName = data.tabname;
                item.tableAlias = data.tableAlias;
              }
            });
          }
          break;
        case 'sorts':
          if (this.conditionsRowIndex === null) {
            this.sorts.push({
              insideCode: data.insideCode,
              field: data.colname,
              fieldNotes: data.colcomment,
              tableName: data.tabname,
              tableAlias: data.tableAlias,
              sortType: '',
              sequence: '',
              $cellEdit: true
            });
          } else {
            this._forEach(this.sorts, (item, itemIndex) => {
              if (this.conditionsRowIndex === itemIndex) {
                item.insideCode = data.insideCode;
                item.field = data.colname;
                item.fieldNotes = data.colcomment;
                item.tableName = data.tabname;
                item.tableAlias = data.tableAlias;
              }
            });
          }
          break;
        case 'groupFields':
          if (this.conditionsRowIndex === null) {
            this.groupFields.push({
              insideCode: data.insideCode,
              field: data.colname,
              fieldNotes: data.colcomment,
              tableName: data.tabname,
              tableAlias: data.tableAlias
            });
          } else {
            this._forEach(this.groupFields, (item, itemIndex) => {
              if (this.conditionsRowIndex === itemIndex) {
                item.insideCode = data.insideCode;
                item.field = data.colname;
                item.fieldNotes = data.colcomment;
                item.tableName = data.tabname;
                item.tableAlias = data.tableAlias;
              }
            });
          }
          break;
        case 'returnFields':
          if (this.conditionsRowIndex === null) {
            this.returnFields.push({
              insideCode: data.insideCode,
              field: data.colname,
              fieldNotes: data.colcomment,
              fieldAlias: '',
              tableName: data.tabname,
              tableAlias: data.tableAlias,
              dataType: '字段',
              mappingApi: '',
              mappingApiName: '',
              type: this.apiInfo.returnType,
              operationMode: '',
              sequence: '',
              $cellEdit: true
            });
          }
          break;
        default:
          this._forEach(this.tableFieldType, (item, itemIndex) => {
            if (this.conditionsRowIndex === itemIndex) {
              item.insideCode = data.insideCode;
              item.field = data.colname;
              item.fieldNotes = data.colcomment;
              item.tableName = data.tabname;
              item.tableAlias = data.tableAlias;
            }
          });
          console.log(this.tableFieldType);
          break;
      }
    },

    /**
     * 表字段信息行点击
     */
    conditionsRowClick(row) {
      this.conditionsRowIndex = row.$index;
    },

    /**
     * 表关联关系行点击
     */
    associationConditionsRowClick(row) {
      this.associationConditionsIndex = row.$index;
    },

    singleChoice(selectData) {
      let commonModalTemSelectedInfo = selectData;
      console.log(commonModalTemSelectedInfo);
      let list = this[this.tableFieldType];
      let repertField = this._find(list, {
        field: commonModalTemSelectedInfo.fieldName,
        insideCode: commonModalTemSelectedInfo.insideCode
      });
      if (repertField) {
        this.$confirm('当前选中的字段已经被添加过了，请重新选择！', '提示', {
          confirmButtonText: '确定',
          type: 'warning'
        });
        return;
      }
      this._forEach(list, (item) => {
        item.isEdit = false;
      });
      switch (this.tableFieldType) {
        case 'associationConditionsLeft':
          this._forEach(this.associationConditions, (item, itemIndex) => {
            if (this.tableFieldIndex === itemIndex) {
              item.leftInsideCode = commonModalTemSelectedInfo.insideCode;
              item.leftField = commonModalTemSelectedInfo.fieldName;
              item.leftFieldNotes = commonModalTemSelectedInfo.fieldComment;
              item.leftTableName = commonModalTemSelectedInfo.tableName;
              item.leftTableAlias = commonModalTemSelectedInfo.tableAlias;
            }
          });
          break;
        case 'associationConditionsRight':
          this._forEach(this.associationConditions, (item, itemIndex) => {
            if (this.tableFieldIndex === itemIndex) {
              item.rightInsideCode = commonModalTemSelectedInfo.insideCode;
              item.rightField = commonModalTemSelectedInfo.fieldName;
              item.rightFieldNotes = commonModalTemSelectedInfo.fieldComment;
              item.rightTableName = commonModalTemSelectedInfo.tableName;
              item.rightTableAlias = commonModalTemSelectedInfo.tableAlias;
            }
          });
          break;
        case 'conditions':
          if (this.tableFieldIndex === null) {
            this.conditions.push({
              insideCode: commonModalTemSelectedInfo.insideCode,
              field: commonModalTemSelectedInfo.fieldName,
              fieldNotes: commonModalTemSelectedInfo.fieldComment,
              tableName: commonModalTemSelectedInfo.tableName,
              tableAlias: commonModalTemSelectedInfo.tableAlias,
              connector: '', //逻辑连接符
              connectorPriority: '',
              operator: '',
              type: '输入参数',
              value: '',
              sequence: '',
              isEdit: true
            });
          } else {
            this._forEach(this.conditions, (item, itemIndex) => {
              if (this.tableFieldIndex === itemIndex) {
                item.insideCode = commonModalTemSelectedInfo.insideCode;
                item.field = commonModalTemSelectedInfo.fieldName;
                item.fieldNotes = commonModalTemSelectedInfo.fieldComment;
                item.tableName = commonModalTemSelectedInfo.tableName;
                item.tableAlias = commonModalTemSelectedInfo.tableAlias;
              }
            });
          }
          break;
        case 'sorts':
          if (this.tableFieldIndex === null) {
            this.sorts.push({
              insideCode: commonModalTemSelectedInfo.insideCode,
              field: commonModalTemSelectedInfo.fieldName,
              fieldNotes: commonModalTemSelectedInfo.fieldComment,
              tableName: commonModalTemSelectedInfo.tableName,
              tableAlias: commonModalTemSelectedInfo.tableAlias,
              sortType: '',
              sequence: '',
              isEdit: true
            });
          } else {
            this._forEach(this.sorts, (item, itemIndex) => {
              if (this.tableFieldIndex === itemIndex) {
                item.insideCode = commonModalTemSelectedInfo.insideCode;
                item.field = commonModalTemSelectedInfo.fieldName;
                item.fieldNotes = commonModalTemSelectedInfo.fieldComment;
                item.tableName = commonModalTemSelectedInfo.tableName;
                item.tableAlias = commonModalTemSelectedInfo.tableAlias;
              }
            });
          }
          break;
        case 'groupFields': {
          let obj = {
            insideCode: commonModalTemSelectedInfo.insideCode,
            field: commonModalTemSelectedInfo.fieldName,
            fieldNotes: commonModalTemSelectedInfo.fieldComment,
            tableName: commonModalTemSelectedInfo.tableName,
            tableAlias: commonModalTemSelectedInfo.tableAlias
          };
          this.groupFields.push(obj);
          break;
        }
        default:
          this._forEach(this[this.tableFieldType], (item, itemIndex) => {
            if (this.tableFieldIndex === itemIndex) {
              item.insideCode = commonModalTemSelectedInfo.insideCode;
              item.field = commonModalTemSelectedInfo.fieldName;
              item.fieldNotes = commonModalTemSelectedInfo.fieldComment;
              item.tableName = commonModalTemSelectedInfo.tableName;
              item.tableAlias = commonModalTemSelectedInfo.tableAlias;
            }
          });
          break;
      }
    },

    /**
     * 子查询中选择查询类API
     * @param index
     */
    openQueryApiModal(index) {
      this.returnFieldsIndex = index;
      this.modalName = 'apiModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择API',
        url: '/api/mes-product/apaas/api/page',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: 'API名称',
            prop: 'zhCnName'
          },
          {
            label: 'API编码',
            prop: 'code'
          },
          {
            label: 'API地址',
            prop: 'url'
          },
          {
            label: 'API类型',
            prop: 'apiType',
            dicData: [
              {
                label: '查询类',
                value: 'QUERY'
              },
              {
                label: '操作类',
                value: 'OPERATION'
              }
            ]
          },
          {
            headerName: '备注',
            field: 'zhCnContent'
          }
        ]
      };
    },

    /**
     * 添加返回字段
     */
    openTabledetailmultiplemodal() {
      //获取表信息配置中已经选择好的表
      if (this.dataTables.length > 0) {
        let dataSet = this._map(this.dataTables, (item) => {
          if (item.tableAlias) {
            item.tableComment = item.tableNotes + '-' + item.tableAlias;
          } else {
            item.tableComment = item.tableNotes;
          }
          return item;
        });
        this.$refs.tabledetailmultiplemodal.modalShow(dataSet);
      } else {
        this.$alert('请先新增表信息', '提示', {
          confirmButtonText: '确定'
        });
      }
    },

    submitData(data) {
      let multipleSelectedData = data;
      multipleSelectedData = this._map(multipleSelectedData, (item) => {
        return {
          insideCode: item.insideCode,
          field: item.fieldName,
          fieldNotes: item.fieldComment,
          fieldAlias: '',
          tableName: item.tableName,
          tableAlias: item.tableAlias,
          dataType: '字段',
          mappingApi: '',
          mappingApiName: '',
          type: this.apiInfo.returnType,
          sequence: ''
        };
      });
      this._forEach(multipleSelectedData, (item) => {
        this.returnFields.push(item);
      });
      let hash = {}; //去重
      this.returnFields = this.returnFields.reduce((preVal, curVal) => {
        if (!hash[curVal.field] && !hash[curVal.tableName]) {
          hash[curVal.field] = true;
          hash[curVal.tableName] = true;
          preVal.push(curVal);
        }
        return preVal;
      }, []);
    },

    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    },

    /**
     * 模态框表格选中数据返回
     */
    getSelectedRows(data) {
      console.log(this.modalName, 'this.modalName');
      if (this.modalName === 'paramsModal') {
        let selectedData = this._map(data, (item) => {
          return {
            code: item.dictKey,
            value: item.dictValue
          };
        });
        let paramMapData = [];
        this._forEach(this.paramsData, (item) => {
          paramMapData.push(item);
        });
        paramMapData.push(...selectedData);

        let hash = {}; //去重
        paramMapData = paramMapData.reduce((preVal, curVal) => {
          hash[curVal.code] ? '' : (hash[curVal.code] = true && preVal.push(curVal));
          return preVal;
        }, []);
        this.paramsData = paramMapData;
        this.paramsList = paramMapData;
        this.conditionsDefaults.value.dicData = this.paramsList;
      } else if (this.modalName === 'tableModal') {
        this._forEach(this.dataTables, (item, index) => {
          item.$cellEdit = false;
        });

        if (this.dataTablesType === 'add') {
          this.dataTables.push({
            insideCode: guid(),
            tableName: data.tabname,
            tableNotes: data.tabcomment,
            tableAlias: '',
            tableAliasNotes: '',
            tableRelation: '',
            associationConditions: [],
            sequence: '',
            $cellEdit: true
          });
        } else {
          this._forEach(this.dataTables, (item, itemIndex) => {
            if (this.dataTablesIndex === itemIndex) {
              item.insideCode = guid();
              item.tableName = data.tabname;
              item.tableNotes = data.tabcomment;
            }
          });
        }
      } else if (this.modalName === 'apiModal') {
        this._forEach(this.returnFields, (item, itemIndex) => {
          console.log(this.conditionsRowIndex);
          if (this.conditionsRowIndex === itemIndex) {
            item.mappingApiCode = data.code;
            item.mappingApiName = data.zhCnName;
          }
        });
      } else if (this.modalName === 'returnFields') {
        this.returnFields.push({
          insideCode: data.insideCode,
          field: data.colname,
          fieldNotes: data.colcomment,
          fieldAlias: '',
          tableName: data.tabname,
          tableAlias: data.tableAlias,
          dataType: '字段',
          mappingApi: '',
          mappingApiName: '',
          type: this.apiInfo.returnType,
          operationMode: '',
          sequence: '',
          $cellEdit: true
        });
      }
      this.$refs.commonModalTemplate.hideModal();
    },

    /**
     * 保存查询API配置
     */
    saveQueryConfigData() {
      console.log(this.$refs.apiForm);
      if (!this.apiInfo.name) {
        this.$confirm('请输入API响应名称！', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        return;
      }
      if (!this.apiInfo.code) {
        this.$confirm('请输入API响应编码！', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        return;
      }
      if (!this.apiInfo.url) {
        this.$confirm('请输入API地址！', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        return;
      }

      //限制关联关系必须填写
      if (this.dataTables.length > 1) {
        if (this.dataTables[this.dataTables.length - 1].associationConditions.length === 0) {
          this.$confirm('请编辑表关联关系！', '提示', {
            confirmButtonText: '确定',
            type: 'warning'
          });
          return;
        }
      }

      let paramMap = {
        id: this.apiFlowId,
        name: this.apiInfo.name,
        code: this.apiInfo.code,
        url: this.apiInfo.url,
        // url: '/paas/v1/module/common/api/execute/query/logical',
        apiType: 'QUERY',
        httpMethod: 'post',
        enabled: true,
        zhCnContent: this.apiInfo.zhCnContent,
        internal: true,
        validation: true,
        validationField: 'stateCode',
        value: 'SYSTEM_SUCCESS',
        httpHeaders: {},
        options: '',
        paramsJson: JSON.stringify(this.paramsData),
        dataTables: JSON.stringify(this.dataTables),
        conditions: JSON.stringify(this.conditions),
        groupFields: JSON.stringify(this.groupFields),
        returnFields: JSON.stringify(this.returnFields),
        sorts: JSON.stringify(this.sorts)
      };

      if (this.apiFlowId) {
        this.apiInfo.paramsJson = JSON.stringify(this.paramsData);
        this.apiInfo.dataTables = JSON.stringify(this.dataTables);
        this.apiInfo.conditions = JSON.stringify(this.conditions);
        this.apiInfo.groupFields = JSON.stringify(this.groupFields);
        this.apiInfo.returnFields = JSON.stringify(this.returnFields);
        this.apiInfo.sorts = JSON.stringify(this.sorts);
        addOrUpdateApi(this.apiInfo).then((res) => {
          this.$message({
            type: 'success',
            message: res.data.msg
          });
          this.getModelFlowInfo(this.apiFlowId);
        });
      } else {
        addOrUpdateApi(paramMap).then((res) => {
          this.$message({
            type: 'success',
            message: res.data.msg
          });
          let apiFlowId = this._get(res, 'data.data.id', '');
          this.$router.replace({ path: '/product/model-manage/searchflow-config/edit', query: { apiId: apiFlowId } });
        });
      }
    },

    /**
     * 返回API流程配置
     */
    onReturn() {
      this.$router.replace('/product/model-manage/api-flow-config');
    }
  }
};
